#include "barrier.h"

void do_barrier_init(barrier_t *barrier, int goal)
{
     barrier->task_num = goal;
     barrier->unfinished_num = goal;
     queue_init(&(barrier->waiting_queue));
}

void do_barrier_wait(barrier_t *barrier)
{
     if (barrier->unfinished_num == 1)
     {
          // clear all the tasks in the waiting queue
          while (!queue_is_empty(&(barrier->waiting_queue)))
          {
               pcb_t *first_task = queue_dequeue(&(barrier->waiting_queue));
               first_task->status = TASK_READY;
               queue_push(&ready_queue, first_task);
          }
          barrier->unfinished_num = barrier->task_num;
     }
     else
     {
          current_running[core_id]->status = TASK_BLOCKED;
          queue_push(&(barrier->waiting_queue), current_running[core_id]);
          barrier->unfinished_num--;
          do_scheduler();
     }
}